<template>
  <div class="factory-cust-chart factory-chart" :index="grpFlter.index">
    <div class="chart-handler" v-if="editable">
      <template v-if="!wrong && showList">
        <el-button type="primary" size="mini" @click="$emit('handleDeep')">深入分析</el-button>
      </template>
      <el-dropdown>
        <i class="el-icon-more"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-edit" @click.native="$emit('editChart')">
            编辑
          </el-dropdown-item>
          <el-dropdown-item icon="el-icon-close" @click.native="$emit('deleteChart')">
            删除
          </el-dropdown-item>
          <template v-if="!wrong">
            <el-dropdown-item @click.native="$emit('export')" class="drop-item">
              <icon-svg name="iconFacExport"></icon-svg>
              导出结果集
            </el-dropdown-item>
            <el-dropdown-item
              icon="el-icon-download"
              @click.native="$emit('downloadChart', { chart: heatChart, name: grpFlter.mainGrp.groupName })"
            >
              下载统计图
            </el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-row :gutter="50">
      <el-col :span="grpFlter.isCompare ? 12 : 24" v-loading="loading">
        <template v-if="!wrong">
          <div
            class="chart-content"
            :id="`factory-profile-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">
              {{ grpFlter.mainGrp.groupName }} <span class="tips">{{ axisTips }}</span>
            </div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content no-record" v-else>
          <template v-if="!loading">
            <div class="chart-title">
              {{ grpFlter.mainGrp.groupName }} <span class="tips">{{ axisTips }}</span>
            </div>
            <div>
              <img src="~@/assets/img/no_records.png" /> <br />
              计算出错
            </div>
          </template>
        </div>
      </el-col>
      <el-col :span="12" v-if="grpFlter.isCompare" v-loading="compare.loading">
        <template v-if="!compare.wrong">
          <div
            class="chart-content"
            :id="`factory-profile-compare-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="compare.showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">
              对比画像
              <span class="tips">{{ axisTips }}</span>
            </div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content no-record" v-else>
          <template v-if="!compare.loading">
            <div class="chart-title">
              对比画像
              <span class="tips">{{ axisTips }}</span>
            </div>
            <div>
              <img src="~@/assets/img/no_records.png" /> <br />
              计算出错
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
    grpFlter: {
      type: Object,
      required: true,
      default: () => {}
    },
    editable: {
      type: Boolean,
      default: true
    },
    grpTotal: {
      // 客户数
      type: Object,
      default: () => {
        return {
          grpTotal: 0,
          compareTotal: 0
        }
      }
    }
  },
  data() {
    return {
      loading: false,
      heatChart: null,
      wrong: false,
      list: [],
      showList: true,
      compare: {
        loading: false,
        heatChart: null,
        wrong: false,
        list: [],
        showList: true
      },
      colorList: ['#0f80ff', '#11ce98', '#f79e2a', '#7886c5', '#e8d318', '#4dad30', '#f3b177']
    }
  },
  computed: {
    axisTips() {
      const tips1 =
        this.grpFlter.mainGrp.tagNm +
        ' X ' +
        (this.grpFlter.subGrp && this.grpFlter.subGrp.labId ? this.grpFlter.subGrp.tagNm : '数值')
      const tips2 =
        (this.grpFlter.subGrp && this.grpFlter.subGrp.labId ? this.grpFlter.subGrp.tagNm : '数值') +
        ' X ' +
        this.grpFlter.mainGrp.tagNm
      return this.grpFlter.mainGrp.graphType === 'bar' ? tips1 : tips2
    }
  },
  methods: {
    setLoading(type = 'default') {
      if (type === 'default') this.loading = true
      this.compare.loading = true
    },
    refreshChart(data = {}) {
      this.wrong = !!data.wrong
      this.list = data.labGrps || []
      this.showList = data.labGrps && data.labGrps.length > 0
      if (this.showList) {
        this.$nextTick(() => {
          if (!this.heatChart)
            this.heatChart = echarts.init(
              document.getElementById(`factory-profile-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
            )
          const _this = this
          let xAxis = []
          let yAxis = []
          let series = []
          let values = data.labGrps.map(item => item.value)
          xAxis = Array.from(
            new Set(
              data.labGrps.map(item => {
                return item.desc || item.code
              })
            )
          )
          yAxis = Array.from(
            new Set(
              data.labGrps.map(item => {
                return item.subDesc || item.subCode
              })
            )
          )
          data.labGrps.forEach(item => {
            let xIndex = xAxis.findIndex(axis => axis === item.desc || axis === item.code)
            let yIndex = yAxis.findIndex(axis => axis === item.subDesc || axis === item.subCode)
            series.push([xIndex, yIndex, item.value])
          })
          xAxis.map(item => {
            return this.grpFlter.mainGrp.valueType == '6' || this.grpFlter.mainGrp.valueType == '7'
              ? item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              : item
          })
          yAxis.map(item => {
            return this.grpFlter.subGrp.valueType == '6' || this.grpFlter.subGrp.valueType == '7'
              ? item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              : item
          })
          let option = {
            title: [
              {
                text: this.grpFlter.mainGrp.groupName,
                textStyle: {
                  fontSize: 16,
                  fontWeight: 700
                }
              },
              {
                text: this.axisTips,
                top: 1,
                left: this.grpFlter.mainGrp.groupName.length * 15 + 20,
                textStyle: {
                  fontSize: 13,
                  fontWeight: 700,
                  color: '#999'
                }
              }
            ],
            tooltip: {
              trigger: 'item',
              confine: true,
              formatter: function(params) {
                return (
                  xAxis[params.data[0]] +
                  ' X ' +
                  yAxis[params.data[1]] +
                  '<br/>数值：' +
                  params.data[2] +
                  '<br/>占比：' +
                  ((params.data[2] / _this.grpTotal.grpTotal) * 100).toFixed(2) +
                  '%'
                )
              }
            },
            grid: {
              top: '40',
              left: 0,
              right: '80',
              bottom: 0,
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: xAxis,
              splitArea: {
                show: true
              }
            },
            yAxis: {
              type: 'category',
              data: yAxis,
              splitArea: {
                show: true
              }
            },
            visualMap: {
              min: Math.min(...values),
              max: Math.max(...values),
              calculable: true,
              top: '40',
              right: 0
            },
            series: [
              {
                type: 'heatmap',
                data: series,
                label: {
                  show: true,
                  formatter: function(params) {
                    const value = params.data[2]
                    const percent = ((value / _this.grpTotal.grpTotal) * 100).toFixed(2) + '%'
                    return `${value} （${percent}）`
                  }
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0,0,0,0.5)'
                  }
                }
              }
            ]
          }
          this.heatChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.heatChart.resize()
          })
        })
      } else {
        if (this.heatChart) {
          this.heatChart.dispose()
          this.heatChart = null
        }
      }
      this.loading = false
    },
    refreshCompareChart(data = {}) {
      this.compare.wrong = !!data.wrong
      this.compare.list = data.labGrps || []
      let showList = data.labGrps && data.labGrps.length > 0
      if (this.compare.list.length) {
        let flag = false
        this.compare.list.forEach(item => {
          if (item.value > 0) flag = true
        })
        showList = flag
      }
      this.compare.showList = showList
      if (showList) {
        this.$nextTick(() => {
          this.compare.heatChart = echarts.init(
            document.getElementById(`factory-profile-compare-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
          )
          const _this = this
          let xAxis = []
          let yAxis = []
          let series = []
          let values = data.labGrps.map(item => item.value)
          xAxis = Array.from(
            new Set(
              data.labGrps.map(item => {
                return item.desc || item.code
              })
            )
          )
          yAxis = Array.from(
            new Set(
              data.labGrps.map(item => {
                return item.subDesc || item.subCode
              })
            )
          )
          data.labGrps.forEach(item => {
            let xIndex = xAxis.findIndex(axis => axis === item.desc || axis === item.code)
            let yIndex = yAxis.findIndex(axis => axis === item.subDesc || axis === item.subCode)
            series.push([xIndex, yIndex, item.value])
          })
          xAxis.map(item => {
            return this.grpFlter.mainGrp.valueType == '6' || this.grpFlter.mainGrp.valueType == '7'
              ? item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              : item
          })
          yAxis.map(item => {
            return this.grpFlter.subGrp.valueType == '6' || this.grpFlter.subGrp.valueType == '7'
              ? item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              : item
          })
          let option = {
            title: [
              {
                text: this.grpFlter.mainGrp.groupName,
                textStyle: {
                  fontSize: 16,
                  fontWeight: 700
                }
              },
              {
                text: this.axisTips,
                top: 1,
                left: this.grpFlter.mainGrp.groupName.length * 15 + 20,
                textStyle: {
                  fontSize: 13,
                  fontWeight: 700,
                  color: '#999'
                }
              }
            ],
            tooltip: {
              trigger: 'item',
              confine: true,
              formatter: function(params) {
                return (
                  xAxis[params.data[0]] +
                  ' X ' +
                  yAxis[params.data[1]] +
                  '<br/>数值：' +
                  params.data[2] +
                  '<br/>占比：' +
                  ((params.data[2] / _this.grpTotal.grpTotal) * 100).toFixed(2) +
                  '%'
                )
              }
            },
            grid: {
              top: '40',
              left: 0,
              right: '80',
              bottom: 0,
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: xAxis,
              splitArea: {
                show: true
              }
            },
            yAxis: {
              type: 'category',
              data: yAxis,
              splitArea: {
                show: true
              }
            },
            visualMap: {
              min: Math.min(...values),
              max: Math.max(...values),
              calculable: true,
              top: '40',
              right: 0
            },
            series: [
              {
                type: 'heatmap',
                data: series,
                label: {
                  show: true,
                  formatter: function(params) {
                    const value = params.data[2]
                    const percent = ((value / _this.grpTotal.grpTotal) * 100).toFixed(2) + '%'
                    return `${value} （${percent}）`
                  }
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0,0,0,0.5)'
                  }
                }
              }
            ]
          }
          this.compare.heatChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.compare.heatChart.resize()
          })
        })
      } else {
        if (this.compare.heatChart) {
          this.compare.heatChart.dispose()
          this.compare.heatChart = null
        }
      }
      this.compare.loading = false
    }
  }
}
</script>

<style lang="scss">
@import './chart.scss';
</style>
